package com.kyzh.core.pager.gamelist


import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.gushenge.core.base.fragment.BaseFragment
import com.gushenge.core.beans.*
import com.gushenge.core.impls.GameImpl
import com.gushenge.core.listeners.ResultListener
import com.gushenge.core.requests.GameRequest
import com.kyzh.core.R
import com.kyzh.core.adapters.*
import com.kyzh.core.adapters.v3.GameListBorderAdapter
import com.kyzh.core.databinding.ItemFooterSortBinding
import com.kyzh.core.utils.setVisibility
import com.kyzh.core.utils.startGameDetailActivity
import com.zhpan.bannerview.BannerViewPager
import kotlinx.android.synthetic.main.fragment_sort.*
import org.jetbrains.anko.support.v4.dip
import org.jetbrains.anko.support.v4.toast

/**
 * A simple [Fragment] subclass.
 */
class SortFragment : BaseFragment(), ResultListener {
    lateinit var leftAdapter: SortLeftAdapter
    var position = 0
    lateinit var chosenAdapter: SortChosenAdapter1
    var listAdapter: GameListBorderAdapter? = null
    val beans = arrayListOf<Game>()
    var type = 1
    private var mp :Int = 1
    private lateinit var banner: BannerViewPager<Slide>
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_sort, container, false)
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
    }

    private fun initView() {
        GameImpl.sort(this)
        initChosen()
    }

    private fun initRight(i: Int, type: Int) {
        root.autoRefresh()
        root.setEnableAutoLoadMore(false)
        root.setOnRefreshListener {
            GameRequest.chosen(i, type) {
                inita(this)
            }
        }

    }

    fun inita(chosen: Chosen) {
        beans.clear()
        val bean = chosen.game.list
        val gameArray = arrayListOf<Game>()
        gameArray.addAll(bean)
        root.finishRefresh()
        root.finishLoadMore()

        beans.addAll(gameArray)
        root.setEnableLoadMore(true)
        root.setEnableOverScrollBounce(true)//是否启用越界回弹
        root.setOnLoadMoreListener {
            if (mp <= chosen.game.max_p) {
                initRight(mp, type)
            } else {
                toast(getString(R.string.noHaveMore))
                root.finishLoadMore()
            }
        }

        if (listAdapter == null) {
            listAdapter = GameListBorderAdapter(R.layout.item_game_border, beans)
            right.layoutManager =
                LinearLayoutManager(requireActivity(), RecyclerView.VERTICAL, false)
            right.adapter = listAdapter
        } else {
            listAdapter?.notifyDataSetChanged()
        }
        listAdapter?.removeAllFooterView()
        if (chosen.game.tuijian.isNotEmpty()) {
            val bind = ItemFooterSortBinding.inflate(layoutInflater)
            bind.revFoot.layoutManager = LinearLayoutManager(requireContext())
            val sortOtherTypeAdapter =
                GameListBorderAdapter(R.layout.item_game_border, chosen.game.tuijian)
            bind.revFoot.adapter = sortOtherTypeAdapter
            listAdapter?.data?.size?.let { listAdapter?.addFooterView(bind.root, it) }
        }

    }


    private var mySlide: ArrayList<Slide> = arrayListOf()
    private var rightList: ArrayList<Game> = arrayListOf()
    private var p: Int = 1
    private fun initChosen() {
        root.autoRefresh()
        root.setEnableAutoLoadMore(false)
        val inflate = LayoutInflater.from(context).inflate(R.layout.header_top_sort, null)
        chosenAdapter = SortChosenAdapter1()
        right.layoutManager = LinearLayoutManager(requireContext())
        right.adapter = chosenAdapter
        root.setOnRefreshListener {
            p = 1
            GameRequest.chosen(p) {
                // 顶部banner
                var banner = inflate.findViewById<BannerViewPager<Slide>>(R.id.banner)
                    .setLifecycleRegistry(lifecycle)
                    .setOnPageClickListener { a, b ->
                        startGameDetailActivity(slide[b].gid)
                    }
                    .setAdapter(BannerAdapter(requireContext()))
                    .setPageMargin(dip(10))
                    .setInterval(5000)
                    .create(slide)
                if (game.p >= game.max_p) {
                    root.finishLoadMoreWithNoMoreData()
                }
                if (slide.isNullOrEmpty()) {
                    chosenAdapter.removeAllHeaderView()
                    inflate.setVisibility(false)
                } else {
                    chosenAdapter.removeAllHeaderView()
                    chosenAdapter.addHeaderView(inflate)
                }
                chosenAdapter.setNewInstance(game.list)
                root.finishRefresh()
                right.adapter = chosenAdapter
                chosenAdapter.setOnItemClickListener { adapter, view, position ->
                    val any = adapter.data[position] as Game
                    startGameDetailActivity(any.gid)
                }
            }
        }
        root.setOnLoadMoreListener {
            p++
            GameRequest.chosen(p) {
                rightList.addAll(this.game.list)
                chosenAdapter.addData(rightList)
                root.finishLoadMore()
                chosenAdapter.setOnItemClickListener { adapter, view, position ->
                    val any = adapter.data[position] as Game
                    startGameDetailActivity(any.gid)
                }
            }
        }
    }

    override fun success(bean: Any) {
        bean as ArrayList<Sort>
        bean[position].color = requireActivity().resources.getColor(R.color.colorPrimary)
        bean[position].bgcolor = requireActivity().resources.getColor(R.color.white)
        leftAdapter = SortLeftAdapter(R.layout.frag_sort_item, bean)
        sort_recyclerview.layoutManager =
            LinearLayoutManager(requireActivity(), RecyclerView.VERTICAL, false)
        sort_recyclerview.adapter = leftAdapter
        leftAdapter.setOnItemClickListener { adapter, view, pos ->
            mp =1
            if (!root.isRefreshing) {
                this.position = pos
                resetColor(bean)
                bean[pos].color = requireActivity().resources.getColor(R.color.colorPrimary)
                bean[pos].bgcolor = requireActivity().resources.getColor(R.color.white)
                leftAdapter.notifyDataSetChanged()
                type = bean[pos].id
                if (position == 0) {
                    initChosen()
                } else {
                    initRight(pos, type)
                }
                return@setOnItemClickListener
            } else {
                toast(getString(R.string.pleaseWaitingLoadDone))
            }
        }


    }

    override fun success(succ: Any, p: Int, max: Int) {
        succ as CodeSort<Game>

    }

    /*
    * 重置左边栏颜色
    * */
    private fun resetColor(lists: MutableList<Sort>) {
        for (i in lists) {
            i.color = requireActivity().resources.getColor(R.color.bg_f7)
            i.bgcolor = requireActivity().resources.getColor(R.color.bg_f7)
        }
    }

    override fun error(error: String) {
        beans.clear()
        root.setEnableLoadMore(false)
        listAdapter = GameListBorderAdapter(R.layout.item_game_border, beans)
        right.layoutManager = LinearLayoutManager(requireActivity(), RecyclerView.VERTICAL, false)
        right.adapter = listAdapter
        listAdapter?.setEmptyView(R.layout.sort_empty)
        root.finishRefresh()
    }

}
